package  
{
	import flash.display.Stage;
	import flash.events.EventDispatcher;
	import assets.trayicon;
	import flash.events.Event;
	import flash.desktop.NativeApplication;
	import flash.desktop.SystemTrayIcon;
	import flash.desktop.DockIcon;
	import flash.display.Bitmap; 
    import flash.display.BitmapData; 
    import flash.display.NativeMenu; 
    import flash.display.NativeMenuItem; 
	import flash.events.MouseEvent;
	
	/**
	 * ...
	 * @author yaempechenki@gmail.com
	 */
	public class TrayIconHelper extends EventDispatcher
	{
		private var _stage:Stage = null;
		public function TrayIconHelper(stage:Stage) 
		{
			_stage = stage;
			_stage.nativeWindow.activate();
		}
		
		public function showTray():void {
			_stage.nativeWindow.visible = false;
			NativeApplication.nativeApplication.icon.bitmaps =  [new trayicon(32, 32)];
    		if (NativeApplication.supportsSystemTrayIcon) { 
				var trayIcon:SystemTrayIcon=NativeApplication.nativeApplication.icon as SystemTrayIcon;
				trayIcon.menu = buildMenu;
				trayIcon.tooltip="Red Button";
				trayIcon.addEventListener(MouseEvent.CLICK, fromTray);
   			} 
			if (NativeApplication.supportsDockIcon) { 
				var dockIcon:DockIcon=NativeApplication.nativeApplication.icon as DockIcon;
				dockIcon.menu = buildMenu;
  			} 
		}
		
		private function get buildMenu():NativeMenu {
			var iconMenu:NativeMenu;
			iconMenu = new NativeMenu();
           	iconMenu.addItem(new NativeMenuItem("Exit"));
			iconMenu.addEventListener(Event.SELECT, menuClick);
			return iconMenu;
		}
		
		private function menuClick(event:MouseEvent):void {
			dispatchEvent(new Event(AppEvent.APP_CLOSE));
		}
		
		public function fromTray(event:MouseEvent = null ):void {
			_stage.nativeWindow.visible = true;
			NativeApplication.nativeApplication.icon.bitmaps = [];
		}
	}

}